import logging
import time
import sys
import glob
import os
sys.path.append('../../')
from frameworks.utils.DirUtil import *
from frameworks.cores.Config import *
import json
class LogUtil:
    def __init__(self,path,business):
        basepath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))).replace("\\", "/")
        parentpath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))).replace("\\", "/")+"/logs/"
        config = Config(basepath)
        apimap = config.getApi()
        env = apimap["base"]
        if parentpath[-1:] == "/":
            self.logdir = parentpath + env[1:] + "/"
        else:
            self.logdir = parentpath + "/" + env[1:] + "/"
        self.business = business
        self.logClear()

    def logClear(self):
        today = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        filenames = glob.glob(self.logdir+"*")
        for file in filenames:
            if file.find(today) < 0:
                os.remove(file)

    def writeLog(self, text):
        today = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        Log_time = time.strftime('%Y-%m-%d %H:%M:%S :', time.localtime(time.time()))
        # 打开文件
        try:
            f = open(self.logdir + self.business + "_" + today + ".txt", "a")
            f.write(Log_time + str(text) + '\n')
            print(Log_time + str(text) + '\n')
            f.close()
        except Exception as e:
            # 访问异常的错误编号和详细信息
            print(e.args)
            print(str(e))
            print(repr(e))

    def writeNodeLog(self, text):
        today = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        Log_time = time.strftime('%Y-%m-%d %H:%M:%S :', time.localtime(time.time()))
        # 打开文件
        try:
            f = open(self.logdir + self.business + "_" + today + ".txt", "a")
            f.write(Log_time + "【"+ str(text) + '】\n')
            print(Log_time + "【"+ str(text) + '】\n')
            f.close()
        except Exception as e:
            # 访问异常的错误编号和详细信息
            print(e.args)
            print(str(e))
            print(repr(e))

    def writeErrorLog(self, text):
        today = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        Log_time = time.strftime('%Y-%m-%d %H:%M:%S :', time.localtime(time.time()))
        # 打开文件
        try:
            f = open(self.logdir + "error_" + self.business + "_" + today + ".txt", "a")
            f.write(Log_time + str(text) + '\n')
            f.close()
        except Exception as e:
            # 访问异常的错误编号和详细信息
            print(e.args)
            print(str(e))
            print(repr(e))